<script lang="ts" setup>
import { createNewsApi, updateNewsApi, getNewsDetailApi } from "@/api/news"
import { type CreateOrUpdateNewsRequestData } from "@/api/news/types/index"
import { type FormInstance, type FormRules, ElMessage, dayjs, UploadUserFile } from "element-plus"
import NewsTypeSelect from "./components/newsTypeSelect.vue"
import { COMPANY } from "./enums"
import { useRouter } from "vue-router"
import { onBeforeUnmount, ref, shallowRef, onMounted } from "vue"
import { Editor, Toolbar } from "@wangeditor/editor-for-vue"
import { CODE_SUCCESS } from "@/utils/service"
import { getImgApi } from "@/api/common/index"
import { computed } from "vue"
import IEditor from "@/components/IEditor/index.vue"

defineOptions({
  // 命名当前组件
  name: "NewsOperate"
})
const router = useRouter()
const id: string = router.currentRoute.value.params.id as string
const loading = ref<boolean>(false)

//#region 增
const DEFAULT_FORM_DATA: CreateOrUpdateNewsRequestData = {
  id,
  title: "",
  type: COMPANY,
  content: "",
  publish_date: dayjs().format("YYYY-MM-DD"),
  author: "",
  cover_url: "",
  tags: "",
  abstract: "",
  source: "",
  isRecommend: "2"
}
const gotoList = () => {
  router.push("/news")
}
const formRef = ref<FormInstance | null>(null)
const formData = ref<CreateOrUpdateNewsRequestData>(JSON.parse(JSON.stringify(DEFAULT_FORM_DATA)))
const formRules: FormRules<CreateOrUpdateNewsRequestData> = {
  title: [{ required: true, trigger: "blur", message: "请输入新闻标题" }],
  content: [{ required: true, trigger: "blur", message: "请输入新闻内容" }],
  type: [{ required: true, trigger: "blur", message: "请选择新闻类型" }],
  publish_date: [{ required: true, trigger: "blur", message: "请选择发布日期" }],
  author: [{ required: true, trigger: "blur", message: "请输入新闻作者" }],
  source: [{ required: true, trigger: "blur", message: "请输入新闻来源" }],
  cover_url: [{ required: true, trigger: "blur", message: "请输入新闻封面" }]
}
const handleCreateOrUpdate = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (!valid) return console.error("表单校验不通过", fields)
    loading.value = true
    const api = !formData.value.id ? createNewsApi : updateNewsApi
    formData.value.publish_date = dayjs(formData.value.publish_date).format("YYYY-MM-DD")
    formData.value.tags = formData.value.tags?.replace(/，/g, ",")

    api(formData.value)
      .then(() => {
        ElMessage.success("操作成功")
        resetForm()
        gotoList()
      })
      .finally(() => {
        loading.value = false
      })
  })
}
const resetForm = () => {
  formRef.value?.clearValidate()
  formData.value = JSON.parse(JSON.stringify(DEFAULT_FORM_DATA))
}

//#region 查
const getNewsDetail = () => {
  if (!id) {
    return
  }
  getNewsDetailApi(id)
    .then(async ({ data }) => {
      formData.value = data
      if (data.cover_url) {
        const { data: fileUrl } = await getImgApi({ path: data.cover_url })

        const { data: fileEnUrl } = await getImgApi({ path: data.cover_url_en || "" })
        file.value = fileUrl
        file_en.value = fileEnUrl
      }
    })
    .catch(() => {
      formData.value = DEFAULT_FORM_DATA
    })
}
onMounted(async () => {
  getNewsDetail()
})
// 富文本
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const editorEnRef = shallowRef()
const toolbarConfig = {
  excludeKeys: ["group-video"]
}
const editorConfig = {
  placeholder: "请输入内容...",
  MENU_CONF: {
    uploadImage: {
      server: "/api/uploadImg",
      fieldName: "file",
      async customInsert(res: ApiResponseData<any>, insertFn: Function) {
        if (res.code === CODE_SUCCESS) {
          const { data: url } = await getImgApi({ path: res.data })
          if (url) {
            insertFn(url, null, url)
          } else {
            ElMessage.error("插入图片失败！")
          }
        }
      }
    },
    uploadVideo: {
      server: "/api/uploadImg",
      fieldName: "file",
      async customInsert(res: ApiResponseData<any>, insertFn: Function) {
        if (res.code === CODE_SUCCESS) {
          const { data: url } = await getImgApi({ path: res.data })
          if (url) {
            insertFn(url, null, url)
          } else {
            ElMessage.error("插入图片失败！")
          }
        }
      }
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
const handleCreatedEn = (editor: any) => {
  editorEnRef.value = editor // 记录 editor 实例，重要！
}
const dialogImgVisible = ref<boolean>(false)
const dialogImgVisibleEn = ref<boolean>(false)

const file = ref<any>()
const file_en = ref<any>()

const handlePreview = async () => {
  if (file.value) {
    dialogImgVisible.value = true
  } else {
    ElMessage.warning("没有可预览的图片")
  }
}
const handleRemove = () => {
  formData.value.cover_url = ""
}
const handleBeforeUpload = (file: any) => {
  return new Promise((resolve, reject) => {
    const isJPG = file.type === "image/jpeg" || "image/png"
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isJPG) {
      ElMessage.error("上传图片只能是 JPG、JPEG、PNG 格式!")
      reject()
    }
    if (!isLt2M) {
      ElMessage.error("上传图片大小不能超过 2MB!")
      reject()
    }
  })
}
const handleSuccess = async (response: any) => {
  if (response.code === CODE_SUCCESS) {
    formData.value.cover_url = response.data
    const { data } = await getImgApi({ path: response.data })
    file.value = data
  }
}
const fileList = computed<UploadUserFile[]>(() => {
  let list: UploadUserFile[] = []
  if (formData.value.cover_url) {
    list = [
      {
        name: formData.value.cover_url.split("/").at(-1) || "",
        url: file.value
      }
    ]
  }
  return list
})

const handlePreviewEn = async () => {
  if (file_en.value) {
    dialogImgVisibleEn.value = true
  } else {
    ElMessage.warning("没有可预览的图片")
  }
}
const handleRemoveEn = () => {
  formData.value.cover_url_en = ""
}
const handleBeforeUploadEn = (file: any) => {
  return new Promise((resolve, reject) => {
    const isJPG = file.type === "image/jpeg" || "image/png"
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isJPG) {
      ElMessage.error("上传图片只能是 JPG、JPEG、PNG 格式!")
      reject()
    }
    if (!isLt2M) {
      ElMessage.error("上传图片大小不能超过 2MB!")
      reject()
    }
  })
}
const handleSuccessEn = async (response: any) => {
  if (response.code === CODE_SUCCESS) {
    formData.value.cover_url_en = response.data
    const { data } = await getImgApi({ path: response.data })
    file_en.value = data
  }
}
const fileListEn = computed<UploadUserFile[]>(() => {
  let list: UploadUserFile[] = []
  if (formData.value.cover_url_en) {
    list = [
      {
        name: formData.value.cover_url_en.split("/").at(-1) || "",
        url: file_en.value
      }
    ]
  }
  return list
})
const recommendOptions = [
  {
    label: "推荐",
    value: "1"
  },
  {
    label: "常规",
    value: "2"
  }
]
</script>

<template>
  <div class="app-container">
    <!-- 新增/修改 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>{{ id === undefined ? "新增新闻" : "修改新闻" }}</h3>
        </div>
      </template>
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="200px" label-position="left">
        <el-form-item prop="title" label="新闻标题">
          <IEditor v-model="formData.title" />
        </el-form-item>
        <el-form-item prop="title_en" label="新闻标题英文">
          <IEditor v-model="formData.title_en" />
        </el-form-item>
        <el-form-item prop="type" label="新闻类型">
          <news-type-select v-model="formData.type" placeholder="请选择" />
        </el-form-item>
        <el-form-item prop="cover_url" label="新闻封面">
          <el-upload
            :file-list="fileList"
            list-type="picture-card"
            class="upload-demo"
            action="/api/uploadImg"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :limit="1"
            :before-update="handleBeforeUpload"
            :on-success="handleSuccess"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">封面图片不能超过 2M.</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item prop="cover_url_en" label="新闻封面英文">
          <el-upload
            :file-list="fileListEn"
            list-type="picture-card"
            class="upload-demo"
            action="/api/uploadImg"
            :on-preview="handlePreviewEn"
            :on-remove="handleRemoveEn"
            :limit="1"
            :before-update="handleBeforeUploadEn"
            :on-success="handleSuccessEn"
          >
            <el-icon><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">封面图片不能超过 2M.</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item prop="tags" label="新闻标签(多标签请用逗号隔开)">
          <el-input v-model="formData.tags" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="tags_en" label="新闻标签英文">
          <el-input v-model="formData.tags_en" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="abstract" label="新闻摘要">
          <el-input v-model="formData.abstract" placeholder="请输入" type="textarea" autosize />
        </el-form-item>
        <el-form-item prop="abstract_en" label="新闻摘要英文">
          <el-input v-model="formData.abstract_en" placeholder="请输入" type="textarea" autosize />
        </el-form-item>
        <el-form-item prop="publish_date" label="发布时间">
          <el-date-picker v-model="formData.publish_date" placeholder="请选择" />
        </el-form-item>
        <el-form-item prop="author" label="作者">
          <el-input v-model="formData.author" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="author_en" label="作者(英文)">
          <el-input v-model="formData.author_en" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="source" label="来源">
          <el-input v-model="formData.source" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="source_en" label="来源(英文)">
          <el-input v-model="formData.source_en" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="isRecommend" label="是否推荐">
          <el-select v-model="formData.isRecommend">
            <el-option v-for="item in recommendOptions" :value="item.value" :label="item.label" :key="item.value" />
          </el-select>
        </el-form-item>

        <el-form-item prop="content" label="新闻内容">
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
              mode="default"
            />
            <Editor
              style="height: 500px; overflow-y: hidden"
              v-model="formData.content"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="handleCreated"
            />
          </div>
        </el-form-item>
        <el-form-item prop="content_en" label="新闻内容英文">
          <div style="border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorEnRef"
              :defaultConfig="toolbarConfig"
              mode="default"
            />
            <Editor
              style="height: 500px; overflow-y: hidden"
              v-model="formData.content_en"
              :defaultConfig="editorConfig"
              mode="default"
              @onCreated="handleCreatedEn"
            />
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="gotoList">取消</el-button>
        <el-button type="primary" @click="handleCreateOrUpdate" :loading="loading">确认</el-button>
      </template>
    </el-card>
    <el-dialog v-model="dialogImgVisible" title="图片预览" width="800" align-center>
      <img :src="file" style="width: 700px" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogImgVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogImgVisibleEn" title="图片预览" width="800" align-center>
      <img :src="file_en" style="width: 700px" />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogImgVisibleEn = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
  :deep(.el-card__body) {
    padding-bottom: 2px;
  }
}

.toolbar-wrapper {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.pager-wrapper {
  display: flex;
  justify-content: flex-end;
}
</style>
